package controllers.tutor;

import controllers.admin.permission.AuthorityController;
import models.permission.User;
import models.tutor.ThemeList;
import models.tutor.Tutor;
import play.Logger;
import play.Play;
import play.db.jpa.JPA;
import play.modules.router.Get;
import play.modules.router.Post;
import services.tutor.TutorService;
import utils.JSON;
import utils.R;

import java.util.Date;
import java.util.Iterator;

/**
 * 导师信息维护 Controller
 * Created by FireFire on 6/26 0026.
 */
public class Tutors extends AuthorityController {


    /**
     * 得到当前的导师信息，将导师的信息封装为JSON数据传递到前台页面。
     *
     */
    @Get("/tts/tutor/index")
    public static void index(){
        User currentUser = currentUser();
        if(currentUser==null) {
            //error("非导师用户，无法访问！");
            String errurl = Play.configuration.getProperty("cas.errorUrl");
            errurl += "?errorCode=002";
            redirect(errurl);
        }

        Tutor tutor = TutorService.currentUserRelatedTutor(currentUser);
        Logger.info("hello world , %s",currentUser);

        render(tutor);
    }

    @Get("/tts/tutor/adminIndex/{code}")
    public static void adminIndex(String code){
        Tutor tutor = TutorService.getTutorByCode(code);
        if(tutor!=null) {
            render(tutor);
        }
        else
            renderText("该导师信息尚未同步，请耐心等待");
    }

    /**
     * 登录用户得到导师信息
     * @param code
     */
    @Get("/tts/tutor/edit/json/{code}")
    public static void json4edit(String code) {
        User currentUser = currentUser();
        if(currentUser==null)
            renderJSON("{}");

        Tutor tutor = TutorService.getTutorByCypheredCode(code);
        if (tutor==null)
            renderJSON("{}");
        else
            renderJSON(JSON.customExpose().toJson(tutor));
    }

    /**
     * 保存或更新item
     * @param item
     */
    @Post("/tts/tutor/theme-list/save")
    public static void saveThemeList(ThemeList item){
        try{
            User currentUser = currentUser();
            Tutor tutor = item.tutor;

            //原先记录的rank自动往插入点之后后排
            Iterator iter = tutor.contents.listIterator();
            while (iter.hasNext()){
                ThemeList olditem = (ThemeList)iter.next();
                if(olditem.theme.code == item.theme.code && olditem.rank>=item.rank &&
                        olditem.id!=item.id) {
                    olditem.rank += 1;
                    olditem.save();
                }
            }

            item.isAuto = false;
            item.lastUpdateDate = new Date();
            item.lastUpdater = currentUser.userName;
            item.save();

            R r = R.ok();
            renderJSON(r);
        }catch(Exception e) {
            error(e.getMessage());
        }
    }


    /**
     * type=0; rank = 0 ;
     * type=1; visible = 0;
     * type=2; visible = 1;
     */
    @Post("/tts/tutor/batchUpdate")
    public static void batchUpdate(int type,int[] ids){
        for(int i=0;i<ids.length;i++){
            ThemeList item = ThemeList.findById(new Long(ids[i]));
            if(item!=null){
                item.isAuto = false;

                if(type==0){
                    item.rank = 0;
                }else if(type==1){
                    item.isOpen = false;
                }else if(type==2){
                    item.isOpen = true;
                }
            }
            item.save();
        }
        R r = R.ok();
        renderJSON(r);
    }


    /**
     * 变更可见性
     * @param id
     */
    @Post("/tts/tutor/toggle")
    public static void toggle(long id) {
        Tutor tutor = Tutor.findById(id);
        if(tutor!=null){
            tutor.isOpen = !tutor.isOpen;
            tutor.save();
        }
    }

    @Get("/tts/tutor/current")
    public static void info(){
        User currentUser = currentUser();
        Tutor tutor = TutorService.currentUserRelatedTutor(currentUser);
    }

}
